package mysql

import (
	"go-gin-demo/models"
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"errors"
)

const secret = "Are you kidding me?"

var (
	ErrorUserExist     = errors.New("用户已存在")
	ErrorUserNotExist  = errors.New("用户不存在")
	ErrorInvalidPasswd = errors.New("用户名或密码错误")
)

// CheckUserExist 检查数据库中是否存在某一个用户
func CheckUserExist(username string) (err error) {
	sqlStr := `select count(user_id) from user where username = ?`
	var count int
	if err := db.Get(&count, sqlStr, username); err != nil {
		return err
	}
	if count > 0 {
		return ErrorUserExist
	}
	return
}

// InsertUser 向数据库中插入一条用户记录
func InsertUser(user *models.User) (err error) {
	// 执行SQL语句入库
	passwd := encryptPasswd(user.Passwd)
	sqlStr := `insert into user(user_id, username, passwd) values(?,?,?)`
	_, err = db.Exec(sqlStr, user.UserID, user.Username, passwd)
	return err
}

// Login 用户登录
func Login(user *models.User) (err error) {
	oPasswd := user.Passwd
	sqlStr := `select user_id, username, passwd from user where username = ?`
	err = db.Get(user, sqlStr, user.Username)
	if err == sql.ErrNoRows {
		return ErrorUserNotExist
	}
	if err != nil {
		return err
	}
	// 判断密码是否正确
	passwd := encryptPasswd(oPasswd)
	if passwd != user.Passwd {
		return ErrorInvalidPasswd
	}
	return
}

// encryptPasswd 密码 md5 加密
func encryptPasswd(oPasswd string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPasswd)))
}
